<?php
namespace App\Core\App;

use Exception;

class CommandApp extends BaseApp
{
    public string $defaultController = 'hello';
    public string $defaultAction = 'index';

    /**
     * 运行指令
     * @param string $cmd
     * @param array $params
     * @throws Exception
     */
    public function run(string $cmd, array $params)
    {
        if(empty($cmd)){
            throw new Exception('请输入指令');
        }
        $pathArr = explode('/',$cmd);
        if(count($pathArr) <= 1){
            throw new Exception('指令错误');
        }
        $controller = $pathArr[0];
        $active = $pathArr[1];
        $controller = ucfirst($controller);
        $class = 'App\\Commands\\' . $controller . 'Command';
        $classPath = __DIR__.'/../../Commands/' . $controller . 'Command.php';
        if(!is_file($classPath)){
            throw new Exception("指令不存在 cmd={$cmd}");
        }
        $controllerClass = new $class();
        if(!method_exists($controllerClass,$active)){
            throw new Exception("指令错误 cmd={$cmd}");
        }
        # 注入参数
        call_user_func_array([$controllerClass,'before'],$params);
        # 运行active
        $controllerClass->$active();
    }
}